import React, { useState, useEffect } from "react";
import {
  Dimensions,
  View,
  Text,
  TextInput,
  ScrollView,
  TouchableOpacity,
  StyleSheet,
  StatusBar,
  Image,
  Platform,
  BackHandler,
} from "react-native";
import PageContainer from "@/components/PageContainer";
import { Modal, Icon } from "@ant-design/react-native";
import useInputWithDone from "@/hooks/useInputWithDone";

// 定义组件的 Props 类型
interface SelectionModalProps {
  visible: boolean;
  title: string;
  listData: any[];
  renderKey?: string;
  onClose: () => void;
  onSelect: (item: any) => void;
  renderItem: (item: any) => React.ReactNode;
}

const SelectionModal: React.FC<SelectionModalProps> = ({
  visible,
  title,
  listData,
  renderKey = "name",
  onClose,
  onSelect,
  renderItem,
}) => {
  const screenHeight = Dimensions.get("window").height;
  const [searchText, setSearchText, handleSearchTextDone] =
    useInputWithDone() as any;
  const statusBarHeight = StatusBar.currentHeight || 0;

  // 优化搜索逻辑
  const getFilteredData = (data: any[], search: string, key: string) => {
    if (!search) return data;
    const searchTerm = search.toLowerCase();
    return data.filter((item) => {
      const value = item[key];
      return (
        typeof value === "string" && value.toLowerCase().includes(searchTerm)
      );
    });
  };

  const [filteredData, setFilteredData] = useState(listData);
  // 新增返回键处理
  // useEffect(() => {
  //   const handleBackPress = () => {
  //     if (visible) {
  //       onClose();
  //       return true; // 阻止默认返回行为
  //     }
  //     return false;
  //   };

  //   BackHandler.addEventListener("hardwareBackPress", handleBackPress);
  //   return () => {
  //     BackHandler.removeEventListener("hardwareBackPress", handleBackPress);
  //   };
  // }, [visible, onClose]);
  const ConutView = () => {
    return (
      <View className="bg-[#000] flex-1 p-[13px]">
        {/* 弹窗头部 */}
        <View className="items-center flex-row h-[46px]">
          <TouchableOpacity onPress={onClose}>
            <Icon name="close" style={{ fontSize: 30 }} />
          </TouchableOpacity>
          <View className="flex-1 flex-row justify-center"></View>
        </View>

        {/* 标题和搜索框 */}
        <Text className="mt-[22px] text-[25px] text-[#fff]">{title}</Text>
        <Text className="text-[#949494] text-[14px] mt-[11px]">
          找不到？请尝试手动搜索
        </Text>
        {/* <View className="mt-[11px] mb-[11px]">
          <TextInput
            style={[styles.input, { fontSize: 16, padding: 12, color: "#fff" }]}
            placeholder="请输入名称进行搜索"
            placeholderTextColor={"rgba(255,255,255,0.3)"}
            onChangeText={setSearchText}
            value={searchText}
            returnKeyType="done"
            onSubmitEditing={() => {
              () => {
                handleSearchTextDone();
                setFilteredData(
                  getFilteredData(listData, setSearchText, renderKey)
                );
              };
            }}
            blurOnSubmit={true}
          />
        </View> */}

        {/* 列表内容 */}
        {listData.length > 0 ? (
          <ScrollView
            showsVerticalScrollIndicator={false}
            showsHorizontalScrollIndicator={false}
            style={{ flex: 1 }}
          >
            <View>
              {listData.map((item, index, arr) => (
                <TouchableOpacity
                  key={item.id || index}
                  onPress={() => onSelect(item)}
                >
                  <View
                    style={{
                      borderBottomWidth: index === arr.length - 1 ? 0 : 1,
                      borderBottomColor: "#303030",
                    }}
                    className="py-[16px]"
                  >
                    {renderItem(item)}
                  </View>
                </TouchableOpacity>
              ))}
            </View>
          </ScrollView>
        ) : (
          <View className="justify-center items-center" style={{ flex: 1 }}>
            <Image
              source={require("@/assets/images/empty.png")}
              className="w-[143px] h-[100px]"
            />
            <Text className="text-[#fff] text-[14px] mt-[10px]">暂无数据</Text>
          </View>
        )}
      </View>
    );
  };
  return (
    <Modal
      popup
      visible={visible}
      animationType="slide-up"
      onRequestClose={true as any}
    >
      <View style={{ height: screenHeight }} className="bg-[#000] flex-1">
        {Platform.OS === "ios" ? (
          <PageContainer>
            <ConutView />
          </PageContainer>
        ) : (
          <ConutView />
        )}
      </View>
    </Modal>
  );
};

const styles = StyleSheet.create({
  input: {
    height: 50,
    backgroundColor: "#25262A",
    borderRadius: 10,
    marginTop: 15,
  },
});

export default SelectionModal;
